package com.zyj.benchmark.sample;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

/**
 * 此例在JDK8之下才有优化的意义
 */
@Warmup(iterations = 1, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 1, time = 1, timeUnit = TimeUnit.SECONDS)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class Sample_09_Blackholes {

    double x1 = Math.PI; //π
    double x2 = Math.PI * 2; //2π

    //基准
    @Benchmark
    public double baseline() {
        return Math.log(x1); //求自然对数, 以e为底
    }

    //错误示例
    @Benchmark
    public double measureWrong() {
        Math.log(x1); //编译器会自动识别, 在JIT的时候直接不执行, 使得JMH结果不准确
        return Math.log(x2); //真正有用的计算
    }

    //正确示例1
    @Benchmark
    public double measureRight_1() {
        //所有计算结果都真实使用了
        return Math.log(x1) + Math.log(x2);
    }

    //正确示例2
    @Benchmark
    public void measureRight_2(Blackhole bh) {
        //如果执行结果不使用编译器会自动优化
        //为了防止编译器自作主张, 这里使用JMH提供的黑洞Blackhole对象对执行结果进行消费
        bh.consume(Math.log(x1));
        bh.consume(Math.log(x2));
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(Sample_09_Blackholes.class.getSimpleName())
                .forks(1)
                .build();
        new Runner(opt).run();
    }


}
